const db=wx.cloud.database()
const pics=db.collection('pics')
const votes=db.collection('votes')
const $=db.command.aggregate
const maxcount=3
Page({
    data:{current:0},
    async onLoad(options){
        let res=await wx.cloud.callFunction({
            name:'login'
        })
        let openid=res.result.openid
        this.setData({
            openid
        })
        let today=new Date()
        today=today.toJSON().slice(0,10)
        res = await votes.aggregate().match({
            _openid:openid
        }).project({
            _openid:1,
            'date':$.dateToString({
                date:'$date',
                format:'%Y-%m-%d'
            })
        }).match({
            date:today
        }).group({
            _id:'$_openid',
            count:$.sum(1)
        }).end()
        console.log(res)
        let count=res.list[0]?.count
        console.log(count)
        this.setData({
            count
        })
        res=await wx.cloud.callFunction({
            name:'getPics'
        })
        let plist=res.result.plist
        let current=0
        if(options._id){
            current=plist.findIndex(v=>{
                return v.fileid==options._id
            })
        }
        this.setData({
            plist,current
        })
        this.setBar(current)
    },
    //async标注函数为异步函数
    async longnew(){
        //await 异步函数中等待promise返回结果
        let res=await wx.chooseMedia({
          count:1,
        })
        let filename=res.tempFiles[0].tempFilePath
        let purefilename=filename.split('/').slice(-1)[0]
        res=await wx.cloud.uploadFile({
            cloudPath:'images/'+purefilename,
            filePath:filename
        })
        let fileid=res.fileID
        res=await pics.add({
            data:{
                fileid
            }
        })
        console.log(res)
        if(res.errMsg.indexOf('ok')>0){
            this.onLoad({
                _id:fileid
            })
        }
    },
    async tap(e){
        if(this.data.count==maxcount){
            wx.showToast({
              title: '超过投票次数',
            })
            return
        }
        let fileid=e.currentTarget.dataset.id
        let res=await votes.add({
            data:{
                fileid,date:db.serverDate()
            }
        })
        wx.reLaunch({
          url: '/pages/work16/index?_id='+fileid,
        })
    },
    change(e){
        console.log(e)
        let current=e.detail.current
        this.setBar(current)
    },
    setBar(current){
        let sz=3  
        if(this.data.count<maxcount){
            let aa=sz-this.data.count
            wx.showToast({
                title: '还有'+aa+'次投票机会',
            })
        }
        wx.setNavigationBarTitle({
            title: current+1+'/'+this.data.plist.length+' '+this.data.plist[current].count+'票',
          })
    }
})